import 'package:dio/dio.dart';
import 'package:jyofservice/bean/check_list_entity.dart';
import 'package:jyofservice/jicha/DealJiCha.dart';
import 'package:jyofservice/jicha/FeeInfo.dart';
import 'package:jyofservice/jicha/JiChaHistroy.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';

class JiChaDetail extends StatefulWidget {
  CheckListEntity? checkListEntity;
  int? state;
  JiChaDetail({this.checkListEntity,this.state});
  @override
  _JiChaDetailState createState() => _JiChaDetailState();
}

class _JiChaDetailState extends State<JiChaDetail> {

  bool isDealShow = false;
  String dealName="";
  bool isloading = true;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.state==0) {
      dealName="立即处理";
      isDealShow = false;
    }else if(widget.state==-100) {
      dealName="加入黑名单";
      isDealShow = false;
    }else if(widget.state==-200){
      dealName="撤销黑名单";
      isDealShow = false;
    }else{
      dealName="";
      isDealShow = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('工单详情',
            style: TextStyle(
                color: Colors.white, fontSize: ScreenUtil().setSp(45))),
        actions: <Widget>[
          PopupMenuButton<String>(
            icon: Icon(Icons.more_horiz),
            offset: Offset(0, 20),
            itemBuilder: (BuildContext context){
              return <PopupMenuItem<String>>[
                this.SelectView('稽查记录', 'B'),
                this.SelectView('收费记录', 'C'),
              ];
            },
            onSelected: (String action) {
              // 点击选项的时候
              switch (action) {
                case 'B':
                  Navigator.push(context, new MaterialPageRoute(builder: (context) {
                    return JiChaHistroy(
                      ybbm: widget.checkListEntity!.ybbm,
                    );
                  }));
                  break;
                case 'C':
                  Navigator.push(context, new MaterialPageRoute(builder: (context) {
                    return FeeInfoPage(
                      ybbm: widget.checkListEntity!.ybbm,
                    );
                  }));
                  break;
              }
            },
          ),
        ],
      ),
      body: Stack(
        alignment: Alignment(0.5, 0.5),
        children: [
          Column(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: SingleChildScrollView(
                  child: Column(
                    children: <Widget>[
                      Container(
                        color: Colors.blue,
                        width: ScreenUtil().screenWidth,
                        height: ScreenUtil().setHeight(100),
                        padding: EdgeInsets.only(left: 10),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            Text(widget.checkListEntity!.ybbm ?? '',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenUtil().setSp(40))),
                            Expanded(
                              flex: 1,
                              child: SizedBox(),
                            ),
                            Icon(
                              Icons.access_time,
                              color: Colors.white,
                            ),
                            Text(widget.checkListEntity!.yhpj ?? '',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenUtil().setSp(40))),
                            SizedBox(
                              width: ScreenUtil().setWidth(30),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        height: ScreenUtil().setHeight(70),
                        padding: EdgeInsets.fromLTRB(10.0, 10.0, 0, 0),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Icon(
                              Icons.person,
                              color: Colors.blue,
                            ),
                            Text(
                              '用户信息',
                              style: TextStyle(
                                  color: Colors.blue,
                                  fontSize: ScreenUtil().setSp(40)),
                            ),
                            Expanded(
                              child: Container(),
                            ),
                          ],
                        ),
                      ),
                      getRow("联系人", widget.checkListEntity!.lxr),
                      getPhoneRow("联系电话", widget.checkListEntity!.lxdh),
                      getRow("住户地址", widget.checkListEntity!.yhmc),
                      getRow("住户编码", widget.checkListEntity!.ybbm),
                      getRow("供暖状态", widget.checkListEntity!.ynzt),
                      getRow("安装状态", widget.checkListEntity!.azzt),
                      getRow("用户类别", widget.checkListEntity!.yhlb),
                      getRow("是否VIP", widget.checkListEntity!.isvip),
                      getRow("收费方式", widget.checkListEntity!.sffs),
                      getRow("收费面积", widget.checkListEntity!.sfmj.toString()),
                      getRow("采暖面积", widget.checkListEntity!.cnmj.toString()),
                    ],
                  ),
                )
              ),
              Offstage(
                  offstage: isDealShow,
                  child: Container(
                    height: ScreenUtil().setHeight(100),
                    width: ScreenUtil().screenWidth,
                    child: GestureDetector(
                      onTap: () {
                        if(widget.state==0) {
                          Navigator.push(context, new MaterialPageRoute(builder: (context) {
                            return DealJiCha(
                              checkListEntity: widget.checkListEntity,
                            );
                          })).then((data) {
                            if (data) {

                              if (mounted) {
                                setState(() {
                                  isDealShow = true;
                                });
                              }
                            }
                          });
                        }else if(widget.state==-100) {
                          //加入黑名单
                          if(isloading) {
                            checkBlakList(context);
                          }else{
                            Fluttertoast.showToast(msg: "正在设置中，请耐心等待。。。");
                          }
                        }else if(widget.state==-200) {
                          if(isloading) {
                            resetBlackList();
                          }else{
                            Fluttertoast.showToast(msg: "正在设置中，请耐心等待。。。");
                          }
                        }

                      },
                      child: Container(
                        color: Colors.blue,
                        child: Center(
                          child: Text(
                            dealName,
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: ScreenUtil().setSp(30)),
                          ),
                        ),
                      ),
                    ),
                  )),
            ],
          ),
          Offstage(
            offstage: isloading,
            child: SpinKitFadingCircle(
              color: Colors.blue,
              size: 50.0,
            ),
          )
        ],
      )

    );
  }

  // 返回每个隐藏的菜单项
  SelectView(String text, String id) {
    return PopupMenuItem<String>(
      value: id,
      child: Text(text),
    );
  }
  Widget getRow(String str1, String? str2) {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          SelectableText(
            str1 ?? '',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(40),
          ),
          Container(
            color: Colors.grey,
            height: ScreenUtil().setHeight(40),
            width: ScreenUtil().setWidth(2),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(20),
          ),
          Expanded(
            flex: 1,
            child: SelectableText(
              str2 ?? '',
              style: TextStyle(
                  color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
            ),
          ),
        ],
      ),
    );
  }

  Widget getPhoneRow(String str1, String? str2) {
    return Container(
      padding: EdgeInsets.only(left: 10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          SelectableText(
            str1 ?? '',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(40),
          ),
          Container(
            color: Colors.grey,
            height: ScreenUtil().setHeight(40),
            width: ScreenUtil().setWidth(2),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(20),
          ),
          Expanded(
              flex: 1,
              child: GestureDetector(
                child: Container(
//                color: Colors.red,
                    alignment: Alignment.centerLeft,
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: SelectableText(
                            str2 ?? '',
//                          maxLines: 2,
//                          overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                color: Colors.black87,
                                fontSize: ScreenUtil().setSp(35)),
                          ),
                        ),
                        Offstage(
                          offstage: str2 != "" ? false : true,
                          child: TextButton.icon(
                              onPressed: () {
                                _launchPhone(str2);
                              },
                              icon: Icon(
                                Icons.phone_in_talk,
                                size: ScreenUtil().setSp(38),
                              ),
                              label: Text(
                                "呼叫",
                                style:
                                TextStyle(fontSize: ScreenUtil().setSp(28)),
                              )),
                        )
                      ],
                    )),
                onTap: () {
                  _launchPhone(str2);
                },
              )),
        ],
      ),
    );
  }

  _launchPhone(str) async {
    if (str != "" && str != null) {
      var url = 'tel:$str';
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        Fluttertoast.showToast(msg: "号码有误,不能拨打电话");
        throw 'Could not launch $url';
      }
    } else {
      Fluttertoast.showToast(msg: "号码有误,不能拨打电话");
    }
  }

  Future submitInfo(String fhjg) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    if(mounted) {
      setState(() {
        isloading = false;
      });
    }
    var dateTime = new DateTime.now();
    String jiChaDate = dateTime.toString().substring(0, 19);
    Response response = await Dio().get(WebConfig().jichaUrl +
        "method=add_fuhe&ybbm=" +
        widget.checkListEntity!.ybbm! +
        "&fhr=" +sharedPreferences.getString("username")!+
        "&fhsj=" +
        jiChaDate +
        "&fhjg=" +fhjg+
        "&fhbz=" +
        "&id="+widget.checkListEntity!.jc_id.toString());
    print(response.data);


    if(response.data["resultCode"]=="100") {
      if(fhjg=="异常") {
        goinblacklist();
      }else{
        Fluttertoast.showToast(msg: "复核成功");
        Navigator.of(context).pop(true);
      }

    }else{
      if(mounted) {
        setState(() {
          isloading = true;
        });
      }
      Fluttertoast.showToast(msg: response.data["resultMsg"]);
    }

  }

  Future goinblacklist() async{
    try {

      Response response = await Dio().get(
        WebConfig().jichaUrl + "method=add_hmd&ybbm="+widget.checkListEntity!.ybbm!+"&czy=sa");
      print(response.data.toString());

      Fluttertoast.showToast(msg: response.data["resultMsg"]);
      if(response.data["resultCode"]=="100") {
        Navigator.of(context).pop(true);
      }
      if(mounted) {
        setState(() {
          isloading = true;
        });
      }

      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  Future resetBlackList() async{
    if(mounted) {
      setState(() {
        isloading = true;
      });
    }
    try {
      Response response = await Dio().get(
        WebConfig().jichaUrl + "method=del_hmd&ybbm="+widget.checkListEntity!.ybbm!+"&czy=sa");
      print(response.data.toString());

      Fluttertoast.showToast(msg: response.data["resultMsg"]);
      if(response.data["resultCode"]=="100") {
        Navigator.of(context).pop(true);
      }
      if(mounted) {
        setState(() {
          isloading = true;
        });
      }

      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  Future checkBlakList(BuildContext context) async{
    final option = await showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
            title: Text("温馨提示"),
            content: Text(
              '是否将该户加入黑名单？\n是：进入黑名单；\n否：进入白名单',
              style: Theme.of(context)
                  .textTheme
                  .titleMedium!
                  .copyWith(color: Theme.of(context).textTheme.bodySmall!.color),
            ),
            actions: <Widget>[
              CupertinoDialogAction(
                child: const Text('是'),
                onPressed: () {
                  Navigator.pop(context, true);
                  submitInfo("异常");
                },
              ),
              CupertinoDialogAction(
                child: const Text('否'),
                onPressed: () {
                  Navigator.pop(context, true);
                  submitInfo("通过");
                },
              )
            ],
          );
          ;
        });
  }
}
